# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/4/13
# @File   : Rule30_LoanAndCard_InspectCnt_6monCheck.py
# @E-mail : zhaochen@bbdservice.com

'''eof
name:近半年贷款审批机构数和信用卡审批查询次数校验
code:LoanAndCard_InspectCnt_6monCheck_2D
tableName:
columnName:
groups:准入>个人征信校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import re
import datetime
from dateutil.relativedelta import relativedelta


reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)

    if occurTimes == 1:
        if table == "":
            return ""
        if table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def Formate(time):
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y-%m-%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y-%m-%d')
            except:
                try:
                    tmp = r.sub('', time)
                    if len(tmp) == 6:
                        date = datetime.datetime.strptime(tmp, '%Y%m').strftime('%Y-%m-%d')
                    else:
                        date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date



# 查询记录  POQ  [1..1] 查询记录信息单元  PH01  [0..*]
#查询日期  PH010R01  [1..1] 查询原因  PH010Q03  [1..1]
def LoanAndCard_InspectCnt_6monCheck():
    data = IC_DSJ_2D['data']
    POQ = getTable(data, 'POQ', occurTimes=1)
    # print POQ
    if POQ is None:
        return u'缺失值'
    elif POQ == [{}] or POQ == "":
        return 0
    else:
        result = []
        PH01 = getTable(POQ[0], 'PH01', 0)
        # print  PH01
        if PH01 is None or PH01 == "":
            return u'缺失值'
        elif PH01 == [{}]:
            return 0
        else:
            for p2 in PH01:
                queryDate = p2.get('PH010R01')
                queryReason = p2.get('PH010Q03')
                queryCode = p2.get('PH010Q02')
                if queryDate in null_type_list or queryCode in null_type_list or queryReason in null_type_list:
                    result.append(None)
                    continue
                queryDateFormat = datetime.datetime.strptime(Formate(queryDate), '%Y-%m-%d')
                sixMonthsAgo = datetime.datetime.now() - relativedelta(months=6)
                today = datetime.datetime.now()
                # sixMonthsAgo = datetime.datetime.now() - pd.tseries.offsets.DateOffset(months=6)
                if queryDateFormat > today:
                    result.append(None)
                    continue
                if queryDateFormat > sixMonthsAgo:
                    if queryReason in null_type_list:
                        result.append(None)
                    elif queryReason in ['02', '03']:
                        result.append(queryDate + queryCode)
                    else:
                        result.append(0)
                else:
                    result.append(0)
            result = filter(lambda x: x is not None, result)
            if len(result) == 0:
                return u'缺失值'
            else:
                # 去重
                result = filter(lambda x: x != 0, result)
                return len(set(result))

result = LoanAndCard_InspectCnt_6monCheck()
